﻿using System;
using EnvDTE;
using Microsoft.VisualStudio.Shell.Interop;

namespace AzurePlugin.Converter
{
    public class ProjectAdapter
    {
        private readonly IVsSolution _solutionService;

        public Project Project { get; private set; }
        public Guid Guid { get; private set; }
        public IVsHierarchy Hierarchy { get; private set; }

        public ProjectAdapter(Project project, IVsSolution solutionService)
        {
            _solutionService = solutionService;

            Project = project;

            Guid = getProjectGuid();
            Hierarchy = getProjectHierarchy();
        }

        public string GetProperty(string name)
        {
            var storage = Hierarchy as IVsBuildPropertyStorage;

            string value;
            storage.GetPropertyValue(name, string.Empty, (uint)_PersistStorageType.PST_PROJECT_FILE, out value);
            return value;
        }

        public void SetProperty(string name, string value)
        {
            var storage = Hierarchy as IVsBuildPropertyStorage;
            storage.SetPropertyValue(name, string.Empty, (uint)_PersistStorageType.PST_PROJECT_FILE, value);
        }

        public void RemoveProperty(string name)
        {
            var storage = Hierarchy as IVsBuildPropertyStorage;
            storage.RemoveProperty(name, string.Empty, (uint)_PersistStorageType.PST_PROJECT_FILE);
        }

        private Guid getProjectGuid()
        {
            Guid guid;
            IVsHierarchy hierarchy;

            _solutionService.GetProjectOfUniqueName(Project.UniqueName, out hierarchy);
            _solutionService.GetGuidOfProject(hierarchy, out guid);

            return guid;
        }

        private IVsHierarchy getProjectHierarchy()
        {
            IVsHierarchy hierarchy;
            _solutionService.GetProjectOfGuid(Guid, out hierarchy);
            return hierarchy;
        }
    }
}
